<template>
  <div class="user-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="部门">
            <el-input v-model="searchForm.department" placeholder="请输入部门" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="userList"
          style="width: 100%"
          border
          stripe
          highlight-current-row
        >
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="department" label="部门" width="150" />
          <el-table-column prop="phone" label="电话" width="120" />
          <el-table-column label="角色" width="150">
            <template #default="scope">
              <el-tag 
                v-for="role in scope.row.roles" 
                :key="role.name"
                :type="role.name === 'ROLE_SUPER_ADMIN' ? 'danger' : role.name === 'ROLE_ADMIN' ? 'warning' : ''"
                class="role-tag"
              >
                {{ getRoleName(role.name) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                link 
                type="danger" 
                @click="handleDelete(scope.row)"
                :disabled="scope.row.roles.some(role => role.name === 'ROLE_SUPER_ADMIN')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="userForm.username" 
            placeholder="请输入用户名"
            :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="userForm.role">
            <el-radio 
              v-for="role in filteredRoleList" 
              :key="role.name" 
              :label="role.value"
            >
              {{ role.displayName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser, 
  getRoleList,
  updateUserRoles 
} from '@/api/auth'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const userList = ref([])
const roleList = ref([])
const userFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  username: '',
  name: '',
  department: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  username: '',
  name: '',
  email: '',
  password: '',
  phone: '',
  department: '',
  role: ''
})

// 表单验证规则
const userFormRules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: dialogType.value === 'add' ? [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ] : [],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}))

// 获取角色名称
const getRoleName = (roleName) => {
  const roleMap = {
    'ROLE_SUPER_ADMIN': '超级管理员',
    'ROLE_ADMIN': '管理员',
    'ROLE_EMPLOYEE': '普通用户'
  }
  return roleMap[roleName] || roleName
}

// 获取角色值（用于表单）
const getRoleValue = (roleName) => {
  // 移除 ROLE_ 前缀
  return roleName.startsWith('ROLE_') ? roleName.substring(5) : roleName
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    const response = await getUserList(params)
    userList.value = response.content
    pagination.total = response.totalElements
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList()
    roleList.value = response
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.page = 1
  fetchUserList()
}

// 添加用户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.keys(userForm).forEach(key => {
    userForm[key] = ''
  })
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

// 编辑用户
const handleEdit = (row) => {
  try {
    dialogType.value = 'edit'
    dialogVisible.value = true
    // 深拷贝用户数据
    const userData = JSON.parse(JSON.stringify(row))
    console.log('编辑用户数据:', userData) // 添加日志
    
    // 重置表单
    Object.keys(userForm).forEach(key => {
      if (key === 'role') {
        // 确保用户至少有一个角色
        if (!userData.roles || userData.roles.length === 0) {
          ElMessage.warning('用户没有任何角色')
          userForm[key] = ''
        } else {
          // 移除 ROLE_ 前缀
          const roleName = userData.roles[0].name
          userForm[key] = roleName.startsWith('ROLE_') ? roleName.substring(5) : roleName
          console.log('设置角色值:', userForm[key]) // 添加日志
        }
      } else if (key === 'password') {
        userForm[key] = '' // 清空密码字段
      } else {
        userForm[key] = userData[key] || ''
      }
    })
    
    // 确保 ID 被正确保存
    userForm.id = userData.id
    
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }
  } catch (error) {
    console.error('编辑用户失败:', error)
    ElMessage.error('编辑用户失败')
  }
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  })
}

// 过滤后的角色列表（不包含超级管理员）
const filteredRoleList = computed(() => {
  return roleList.value
    .filter(role => role.name !== 'ROLE_SUPER_ADMIN')
    .map(role => ({
      ...role,
      displayName: getRoleName(role.name),
      value: getRoleValue(role.name)
    }))
})

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const formData = { ...userForm }
        console.log('提交的表单数据:', formData) // 添加日志
        
        // 检查角色是否为空
        if (!formData.role) {
          ElMessage.error('请选择用户角色')
          return
        }

        // 确保角色名称格式正确
        const roleToUpdate = formData.role.startsWith('ROLE_') ? formData.role : `ROLE_${formData.role.toUpperCase()}`
        delete formData.role

        if (dialogType.value === 'add') {
          await createUser(formData)
          ElMessage.success('添加成功')
        } else {
          // 确保 id 是数字类型
          const userId = parseInt(formData.id)
          if (isNaN(userId)) {
            throw new Error('无效的用户ID')
          }
          
          try {
            // 更新用户基本信息
            const updateData = {
              username: formData.username,
              name: formData.name,
              email: formData.email,
              phone: formData.phone || '',
              department: formData.department || ''
            }
            
            console.log('更新用户数据:', updateData) // 添加日志
            await updateUser(userId, updateData)
            
            console.log('更新角色:', roleToUpdate) // 添加日志
            await updateUserRoles(userId, [roleToUpdate])
            
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchUserList()
          } catch (error) {
            console.error('更新失败:', error)
            if (error.response?.status === 403) {
              ElMessage.error('您没有权限执行此操作')
            } else {
              ElMessage.error(error.response?.data?.message || '更新失败')
            }
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchUserList()
}

// 页码变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchUserList()
}

onMounted(() => {
  fetchUserList()
  fetchRoleList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  height: 100%;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  border-bottom: 1px solid #ebeef5;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
}

.table-section {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

:deep(.el-table) {
  flex: 1;
  min-height: 0;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  min-height: 200px;
  max-height: calc(100vh - 400px);
}

:deep(.el-table .cell) {
  padding: 8px;
}

:deep(.el-table--striped .el-table__row--striped td) {
  background-color: #fafafa;
}

.pagination-section {
  position: relative;
  z-index: 1;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: auto;
}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
  justify-content: flex-end;
  white-space: nowrap;
}

:deep(.el-card__body) {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

.role-tag {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .search-form {
    .el-form-item {
      margin-right: 16px;
    }
  }
}

@media screen and (max-width: 768px) {
  .search-form {
    .el-form-item {
      width: 100%;
      margin-right: 0;
    }
  }
}
</style>
